package cn.shujuhai.common.pluging.email;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.shujuhai.cms.domain.ToEmail;
import jakarta.activation.DataSource;
import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Map;

/**
 * @Author: NiuYaHu
 * @Date: 2024/12/23 10:57
 * @Description:
 **/
@Component
@Slf4j
@RequiredArgsConstructor
public class MailUtil {

    private final JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String from;
    @Value("${template.url}")
    private String url;

    /**
     * 发送HTML格式邮件的方法
     *
     * @param toEmail 接收
     */
    public void htmlEmail(ToEmail toEmail) throws Exception {
        // 创建一个 MIME 消息
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper mineHelper = new MimeMessageHelper(message, true); // true 表示支持附件和嵌入内容

        // 设置发件人
        mineHelper.setFrom(from);
        // 设置收件人
        mineHelper.setTo(toEmail.getTo());
        // 设置邮件主题
        mineHelper.setSubject(toEmail.getSubject());


        String content = toEmail.getContent();
        Document document = Jsoup.parse(content);
        Element element = document.select("code#toName").first();
        if (element != null) {
            element.text(toEmail.getToName());
        }

        // 设置邮件内容 (带 HTML 格式)
        mineHelper.setText(document.html(), true);

        // 处理附件
        if (StrUtil.isNotEmpty(toEmail.getAttachment())) {
            String filePath = url + toEmail.getAttachment();
            File attachmentFile = new File(filePath);
            String suffix = FileUtil.getSuffix(filePath);
            mineHelper.addAttachment("附件." + suffix, attachmentFile);
        }

        // 处理多媒体（cid 引用的内容）
        if (toEmail.getMultimedia() != null && !toEmail.getMultimedia().isEmpty()) {
            for (Map.Entry<String, DataSource> entry : toEmail.getMultimedia().entrySet()) {
                String cid = entry.getKey(); // cid 名称
                DataSource dataSource = entry.getValue(); // 对应的 Base64 编码内容
                mineHelper.addInline(cid, dataSource);
            }
        }
        // 发送邮件
        mailSender.send(message);
    }
}